package algorithms;

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

public class RadixSort {
    public static void main(String[] args) {
        int[] arr = new int[]{22, 1, 321, 5, 12, 775, 89, 2480, 49, 625};
        System.out.println(Arrays.toString(arr));
        radixSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void radixSort(int[] arr) {
        //数组中的最大数
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }

        int maxLength = String.valueOf(max).length();
        Queue[] temp = new PriorityQueue[10];
        for (int i = 0; i < temp.length; i++) {
            temp[i] = new PriorityQueue();
        }

        for (int i = 0, n = 1; i < maxLength; i++, n *= 10) {
            for (int j = 0; j < arr.length; j++) {
                //余数
                int ys = arr[j] / n % 10;
                temp[ys].add(arr[j]);
            }

            //遍历后存入，用于下次循环
            int index = 0;
            for (int k = 0; k < temp.length; k++) {
                while (!temp[k].isEmpty()) {
                    arr[index] = (int) temp[k].poll();
                    index++;
                }
            }
        }
    }
}